export default class test_websocket extends Laya.Script {
    
    private socket:Laya.Socket;              //创建websocket对象
    private show_log:Laya.Text;
    private text_input:Laya.TextInput;
    private send_btn:Laya.Button;
    private text_area:Laya.TextArea;
    private player_circle:Laya.Sprite;

    constructor() { super(); }
    
    onEnable(): void 
    {
        this.initParams()
        //创建websocket对象
        this.socket = new Laya.Socket();
        //建立连接
        //url格式->通讯协议://ip地址或者域名:端口号
        this.socket.connectByUrl("ws://localhost:8080");
        //建立监听
        this.socket.on(Laya.Event.OPEN, this, this.openHandler);
        this.socket.on(Laya.Event.MESSAGE, this, this.receiveHandler);
        this.socket.on(Laya.Event.CLOSE, this, this.closeHandler);
        this.socket.on(Laya.Event.ERROR, this, this.errorHandler);
    }
    initParams()
    {
        //创建消息显示文本
        this.show_log=new Laya.Text();
        this.show_log.color="red";
        this.show_log.fontSize=35;
        this.owner.addChild(this.show_log);
        this.text_input=this.owner.getChildByName("text_input") as Laya.TextInput;
        this.send_btn=this.owner.getChildByName("send_btn") as Laya.Button;
        //给send_btn绑定鼠标点击事件
        this.send_btn.on(Laya.Event.CLICK,this,this.onSendBtn);
        this.text_area=this.owner.getChildByName("text_area") as Laya.TextArea;
        this.player_circle=this.owner.getChildByName("player") as Laya.Sprite;
    }
    onSendBtn()
    {
        //获取输入框里面的文本
        let str=this.text_input.text;
        //发送消息到服务端
        this.socket.send(str);
        this.MovePlayer(str);
        
    }

    MovePlayer(data:string)
    {
        if(data=='left')
        {
            Laya.Tween.to(
                this.player_circle,
                {x:this.player_circle.x-=10},
                200
            )
        }
        if(data=='right')
        {
            Laya.Tween.to(
                this.player_circle,
                {x:this.player_circle.x+=10},
                200
            )
        }
        if(data=='up')
        {
            Laya.Tween.to(
                this.player_circle,
                {y:this.player_circle.y-=10},
                200
            )
        }
        if(data=='down')
        {
            Laya.Tween.to(
                this.player_circle,
                {y:this.player_circle.y+=10},
                200
            )
        }
    }

    /**连接成功的回调 */
    openHandler()
    {
        this.text_area.text="连接服务器成功\n"
    }
    /**接受到消息的回调 */
    receiveHandler(data:any)
    {
        this.MovePlayer(data);
        this.text_area.text+="收到的消息->"+data+"\n"
    }
    /**连接关闭的回调 */
    closeHandler(){}
    /**发生错误的回调 */
    errorHandler(){}

    onDisable(): void {
    }
}